package de.reminder.client.widgets;

import java.util.List;

import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.SuggestBox.SuggestionDisplay;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;

import de.reminder.client.MySimpleReminder;
import de.reminder.shared.model.FacebookUser;

public class UserTile extends Composite {

	private static final int statusAccepted = 1;
	private static final int statusTentative = 2;
	private static final int statusRejected = 3;
	private static final int statusSuggesting = 4;
	
	private AbsolutePanel main;
	private Image imageUser;
	private Label labelName;
	private SuggestBox suggestboxName;
	private int status;
	private FacebookUser user;
	private EditUsers parent;
	
	public UserTile(EditUsers parent){
		this.parent = parent;
		
		main = new AbsolutePanel();
		main.setPixelSize(140,120);
		main.getElement().setClassName("UserTile");
		main.getElement().setId("Rahmen");
		
		imageUser = new Image("images/userTile/userTile-unknown.png");
		imageUser.setPixelSize(80, 80);
		imageUser.addStyleName("PictureFrame");
		main.add(imageUser,30,10);
		
		labelName = new Label("Unknown User");
		labelName.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		labelName.setPixelSize(110, 10);
		labelName.addStyleName("Handwritten");
		main.add(labelName,15,92);
		
		initWidget(main);
	}
	
	private void onEnteredSuggestion(String name){
		suggestboxName.setVisible(false);
		labelName.setVisible(true);
		labelName.setText(name);
		for(FacebookUser u : MySimpleReminder.currentUser.getFriends()){
			if(u.getName().equals(name)){
				this.user = u;
				break;
			}
		}
		imageUser.setUrl(user.getProfilePictureURL());
		status = statusTentative;
		parent.setInputFinished(user);
	}
	
	public void setSuggesting(MultiWordSuggestOracle oracle){
		if(status == statusSuggesting)
			return;
		
		suggestboxName = new SuggestBox(oracle);
		suggestboxName.getElement().setId("InputName");
		suggestboxName.addStyleName("Handwritten");
		suggestboxName.setPixelSize(90, 10);
		main.add(suggestboxName,20,92);
		
		labelName.setVisible(false);
		
		suggestboxName.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
			@Override
			public void onSelection(SelectionEvent<Suggestion> event) {
				onEnteredSuggestion(event.getSelectedItem().getReplacementString());
			}
		});		
		status = statusSuggesting;
		suggestboxName.setFocus(true);
	}
}